import {Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {ValidateProvider} from "../../providers/validate/validate";
import {ConfigProvider} from "../../providers/config/config";
import {HttpServicesProvider} from "../../providers/http-services/http-services";
import {StorageProvider} from "../../providers/storage/storage";
import {UtilsProvider} from "../../providers/utils/utils";
import {WechatProvider} from "../../providers/wechat/wechat";
import {UrlProvider} from "../../providers/url/url";
import {CommonProvider} from "../../providers/common/common";

@IonicPage({
    segment: 'information/detail/:id',
    defaultHistory: ['HomePage','InformationPage']
})
@Component({
    selector: 'page-information-detail',
    templateUrl: 'information-detail.html',
})
export class InformationDetailPage {
    @ViewChild('share') share;
    data: any;
    amoy_id: number;
    userinfo = {};
    see_num: any;
    detail = {};
    paylist: any;
    topinfo = {};
    owner: any;
    token:string;
    see_pay_info:any;
    click_pay_info:any;
    //请求数据参数
    params = {};
    //信息是否被收藏
    collected: boolean = false;
    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public httpService: HttpServicesProvider,
        public validate: ValidateProvider,
        public config: ConfigProvider,
        public storage: StorageProvider,
        public util: UtilsProvider,
        public wechat: WechatProvider,
        public url: UrlProvider,
        public common: CommonProvider
    ) 
    {
        // if (!this.validate.checkLogin()) {
        //     this.navCtrl.push('LoginPage');
        //     this.navCtrl.push('InformationDetailPage')
        // }
    }
    ionViewWillEnter() {   
        this.amoy_id = this.navParams.get('id');
        this.token = this.config.getToken();
        this.params['token'] = this.token;
        if(this.storage.get('shareData')){
            let shareData = JSON.parse(this.storage.get('shareData'));
            this.params['share_token'] = shareData['token'];
        }
    }
    ionViewCanEnter(){        
        return this.validate.checkLogin();
    }
    ionViewDidEnter() {        
        this.getData();
    }

    /**
     * 获取数据
     * */
    getData() {
        let loading = this.util.loading();
        loading.show();
        let apiUrl = "/task_info/recruit_detail/id/" + this.amoy_id;
        this.httpService.requestPostData(apiUrl, this.params,response => {
            loading.close();
            if(response['code'] == 200){
                //清除分享数据
                this.storage.remove('shareData');
                //全部数据
                this.userinfo = response['data']['userinfo'];
                this.see_num = response['data']['see_num'];
                this.detail = response['data']['detail'];
                this.paylist = response['data']['paylist'];
                this.topinfo = response['data']['topinfo'];
                this.owner = response['data']['is_self'];
                this.see_pay_info = response['data']['see_pay_info'];
                this.collected = response['data']['has_collect'];
                this.click_pay_info = response['data']['surplus_click_num'];

                this.wechat.getWxConfig(()=>{
                    // this.wechat.wxShareMoments({shareNumber:1, shareTitle:'', amoyId: this.amoy_id});
                    // this.wechat.wxShareFriend({shareNumber:1, shareTitle:'', amoyId: this.amoy_id});
                    this.shareResult();
                });

            }else{
                this.util.presentAlert(response['message']);
                this.navCtrl.pop();
            }
        });
    }

    /**
     * 跳转页面
     * */
    pageRedirect(page,data={}){
        this.navCtrl.push(page,data).then(success=>{
            if(success !== true){//页面需要登录后跳转
                this.navCtrl.push('LoginPage',data);
            }
        })
    }

    /**
     * 点赞
     * */
    collect(amoy_id){
        this.common.collect(amoy_id,(response)=>{
            if(response.code == 200){
                this.getData();
            }
        });
    }

    /**
     * 付费查看
     * */
    paySee(){
        let apiUrl = "/user_info/check_level";
        this.httpService.requestPostData(apiUrl,{
            token: this.config.getToken()
        }, (response)=>{
            if(response['error'] != 200 || response['reg_step'] != 2){
                this.util.presentConfirm('您无权使用此功能，请完善注册资料；现在去完善？', ()=>{
                    this.navCtrl.push('RegisterPage');
                });
            }else{
                this.util.presentConfirm('当前内容为付费查看内容，您需要支付' + this.see_pay_info['see_pay_price'] + '元', ()=>{
                    let postData = {
                        amoy_id: this.amoy_id,
                        token: this.token,
                        see_pay_price: this.see_pay_info['see_pay_price']
                    };
                    this.httpService.requestPostData('/task_info/pay_see_handle', postData, (response)=>{
                        if(response['error'] == 200){
                            this.util.presentAlert('付费成功');
                            this.getData();
                        }else if(response['error'] == 400){
                            this.util.presentConfirm('当前账户余额不足，现在去充值？',()=>{
                                // this.storage.set('backPage',JSON.stringify({page: 'InformationDetailPage', params: {amoy_id: this.amoy_id}}));
                                this.common.setBackPage('InformationDetailPage',{id: this.amoy_id});
                                this.navCtrl.push('MoneyRechargePage');
                            })
                        }
                    })
                }, ()=>{

                });
            }
        });



    }


    /**
     * 分享结果
     * */
    shareResult(title='餐饮信息海量发（淘鲜生餐饮圈）'){
        //分享到朋友圈
        let userInfo = JSON.parse(this.storage.get('userInfo'));
        this.wechat.wxShareMoments({shareNumber: 1, shareTitle: title, amoyId: this.amoy_id, userId:userInfo.user_id},()=>{
            let apiUrl = "/task_info/insert_share";
            this.httpService.requestPostData(apiUrl, {
                token:this.token,
                amoy_id: this.amoy_id
            },() => {
                this.getData();               
            });
        }, ()=>{

        });

        //分享到朋友
        this.wechat.wxShareFriend({shareNumber: 1, amoyId: this.amoy_id, shareTitle: title, userId:userInfo.user_id}, ()=>{
            let apiUrl = "/task_info/insert_share";
            this.httpService.requestPostData(apiUrl, {
                token:this.config.getToken(),
                amoy_id: this.amoy_id
            },() => {
                this.getData();
            });
        });
    }
}
